package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.bwie.common.constants.Constants;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.LoginRequest;
import com.bwie.common.domain.response.LoginResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.exception.LoginException;
import com.bwie.remote.UserRemote;
import com.bwie.service.LoginService;
import com.bwie.sms.SendSmsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @className: LoginServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 刘茂锴
 * @date: 2025/10/13 10:33
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserRemote userRemote;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SendSmsUtils sendSmsUtils;

    //发送短信验证码
    @Override
    public void phoneCode(String phone) {
        if(StrUtil.isBlank(phone)){
            throw new LoginException("请输入手机号");
        }
        if (!phone.matches("1[3-9][0-9]{9}")){
            throw new LoginException("手机号码格式不正确");
        }
        //判断该手机号是否已经发送过短信验证码
        Boolean b = redisTemplate.hasKey(phone);
        if (b){
            throw new LoginException("验证码已发送，于5分钟后重试");
        }
        //生成验证码
        String code = RandomUtil.randomNumbers(4);
        //将验证码存储到redis中
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        //工具类发送短信验证码
        sendSmsUtils.sendSms(phone, JSONObject.toJSONString(new HashMap<String,String>(){{
            put("code",code);
        }}));
    }

    //登录
    @Override
    public LoginResponse loginUser(LoginRequest loginRequest) {
        //获取用户信息
        Result<User> userResult = userRemote.selectPhoneByUser(loginRequest.getPhone());
        if (userResult.getCode()== Constants.ERROR){
            throw new LoginException("用户信息调用失败...");
        }
        User loginUser = userResult.getData();
        if (loginUser==null){
            throw new LoginException("不存在该用户");
        }
        //验证短信验证码是否正确
        String phoneCode = (String) redisTemplate.opsForValue().get(loginRequest.getPhone());
        if (phoneCode != null && !phoneCode.equals(loginRequest.getPhoneCode())) {
            throw new LoginException("验证码输入错误");
        }

        Map<String, Object> map = new HashMap<>();
        //生成唯一标识
        String userKey = IdUtil.fastSimpleUUID();
        map.put(JwtConstants.USER_KEY,userKey);
        //生成token
        String token = JwtUtils.createToken(map);
        //将用户信息存储到redis中
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey,loginUser,30,TimeUnit.MINUTES);

        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setToken(token);
        loginResponse.setShiJ("30MIN");
        return loginResponse;
    }
}
